package com.sky.utils;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 工具类,实现阿里云有关的功能,比如文件上传,列表查询,删除
 *
 * @Author mr.zhang
 * Date 2025/5/21 1:24
 */
@Component
public class AliyunOssOperator {

    @Autowired
    private AliyunOssProperties aliyunOssProperties;


    public String upload(String originFilename,byte[] bytes){
        String bucketName = aliyunOssProperties.getBucketName();
        String region = aliyunOssProperties.getRegion();

        String accessKeyId = aliyunOssProperties.getAccessKeyId();
        String accessKeySecret = aliyunOssProperties.getAccessKeySecret();

        String endpoint = aliyunOssProperties.getEndpoint();

        //获取文件后缀名,比如图片就是.png或者.jpg
        String extName = originFilename.substring(originFilename.lastIndexOf("."));
        //获取当前日期,充当存储的文件夹,并进行格式化
        String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
        //设置完整的objectName路径
        String objectName = dir + "/" + IdUtil.fastSimpleUUID() + extName;
        //获取阿里云实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //将问阿金内容上传到阿里云指定的桶里,并且保存为一个对象,路径由objectName指定
        ossClient.putObject(bucketName,objectName,new ByteArrayInputStream(bytes));
        //使用写的阿里云配置类,进行关闭


        //返回值
        return "https://" + bucketName + "." + region + ".aliyuncs.com/" + objectName;
    }
}
